package com.wy._02io.fileUtil;

import com.wy._02io.EncodingConstant;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.List;

public class WriteFile {

    /**
     * 写内容到文件
     * @param filePath 文件路径
     * @param lines 内容 行
     * @param ifOverlayExists 文件如果存在是否覆盖，如果不覆盖就追加到文件后面
     * @param charset 写入的时候编码
     */
    public static void write(String filePath, List<String> lines, boolean ifOverlayExists, Charset charset) {
        Path path = Paths.get(filePath);
        StandardOpenOption[] options = ifOverlayExists ?
                new StandardOpenOption[]{StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING} :
                new StandardOpenOption[]{StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.APPEND};

        try (BufferedWriter writer = Files.newBufferedWriter(path, charset, options)) {
            for (String line : lines) {
                writer.write(line);
                writer.newLine(); // 添加换行符
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
